﻿using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NLog.Web;
using System.Collections.Generic;

namespace MQTT.Client.Host
{
    class Program
    {
        static void Main(string[] args)
        {

            BuildWebHost(args).Run();
        }

        private static IWebHost BuildWebHost(string[] args)
        {

            var _params_ = Read(args);
            string url = _params_.ContainsKey("url") ? _params_["url"] : $"http://*:{(_params_.ContainsKey("port") ? _params_["port"] : "5000")}";


            return WebHost.CreateDefaultBuilder(args)
               .ConfigureAppConfiguration((hostingContext, config) =>
               {
                   var env = hostingContext.HostingEnvironment;
                   config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                   config.AddEnvironmentVariables();
               })
               .ConfigureLogging((hostingContext, logging) =>
               {
                   logging.ClearProviders();
                   logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
               })
               .UseStartup<Startup>()
               .UseNLog()
               .UseUrls(url)
               .Build();
        }

        /// <summary>
        /// 读取参数 
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static IDictionary<string, string> Read(string[] args)
        {
            Dictionary<string, string> _params = new Dictionary<string, string>();
            for (var i = 0; i < args.Length; i++)
            {
                var p = args[i];
                if (p.StartsWith("--"))
                {
                    //参数
                    _params.Add(p.Replace("--", ""),
                        ((i < args.Length - 1) && !args[i + 1].StartsWith("--")) ? args[i + 1] : "TRUE");
                }
            }
            return _params;
        }
    }
}
